package com.getword.service.impl;

import com.getword.domain.City;
import com.getword.domain.School;
import com.getword.mongodao.CityRepository;
import com.getword.mongodao.SchoolRepository;
import com.getword.service.SchoolService;
import com.getword.web.model.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SchoolServiceImpl implements SchoolService {
    @Autowired
    private SchoolRepository schoolRepository;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private CityRepository cityRepository;

    @Override
    public Result searchByName(String name) {
        Query query = new Query();
        query.limit(20);
        query.addCriteria(Criteria.where("schoolName").regex(".*"+name+".*"));
        List<School> schools = mongoTemplate.find(query, School.class);
        // 城市名称
        for(School s : schools){
            // 省
            s.setProvinceName(cityRepository.findCityById(s.getProvinceId()).getName());
            City county = cityRepository.findCityById(s.getCountyId());
            s.setCountyName(county.getName());
            s.setCityName(cityRepository.findCityById(county.getParentId()).getName());
        }
        return Result.success(schools);
    }
}
